<template>
    <div>
        <el-container>
            <el-header>
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="4">
                        <span style="font-size: 20px; font-weight: 1000; color: white">
                            <el-icon><HomeFilled /></el-icon>{{ $t('菜单设置') }}
                        </span>
                    </el-col>
                    <el-col :span="20">
                        <div style="float: right">
                            <UiSet :type="2" :index="0" :Prop="uiSectionList" :comid="componentId"  v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                        </div>
                    </el-col>
                </el-row>
            </el-header>
            <el-main style="padding: 0%">
                <div>
                    <el-card style="height: auto">
                        <el-form :model="findform" :inline="true" label-width="100px">
                            <el-row :gutter="10">
                                <template v-for="(item, index) in Stores.comui[componentId][0].baseProps">
                                    <el-col v-if="item.visible && item.ismore == false" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                        <el-form-item :label="I(item.label, item.labeleng)">
                                            <template #default>
                                                <el-input clearable v-model="findform[item.prop]" :id="item.prop" />
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                </template>
                                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                    <el-form-item>
                                        <el-button color="#e1d8d8" round :icon="Refresh" @click="resetForm()" id="reset">{{ $t('重置') }}</el-button>
                                        <el-button v-loading="loading" type="primary" round :icon="Search" @click="gettablelist()" id="find">{{ $t('查找') }}</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-card>
                    <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><Grid /></el-icon>{{ $t('列表数据') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <el-row justify="end" :gutter="10">
                                <el-button v-loading="loading" type="primary" :icon="Plus" round @click="append()">{{ $t('新增') }}</el-button>
                                <UiSet :type="1" :index="0" :Prop="uiSectionList" :comid="componentId"  v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-card>
                        <vxe-table :loading="loading" :data="tablelist" border height="400" :mouse-config="{ selected: true }" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }">
                            <vxe-column v-for="(column, index) in Stores.comui[componentId][0].tableProps" :field="column.prop" :title="column.label" :width="column.width" :fixed="column.fixed" :align="column.align">
                                <template #header>
                                    <div v-if="column.type === 'checkbox'">
                                        <el-checkbox v-model="Allcheck" @change="CheckAllChange" />
                                    </div>
                                    <div v-else>
                                        {{ I(column.label, column.labeleng) }}
                                    </div>
                                </template>
                                <template #default="{ row, rowIndex }">
                                    <div v-if="column.type === 'checkbox'">
                                        <el-checkbox v-model="row['checked']" />
                                    </div>
                                    <div v-else-if="column.prop === 'state'">
                                        <el-tag v-if="row.state === 1" effect="dark" round type="primary">{{ $t('启用') }}</el-tag>
                                        <el-tag v-if="row.state !== 1" effect="dark" round type="info">{{ $t('停用') }}</el-tag>
                                    </div>
                                    <div v-else-if="column.type === 'action'">
                                        <el-button size="large" type="success" link @click="lookdetail(rowIndex, row, false)">
                                            {{ $t('查看') }}
                                        </el-button>
                                        <span style="margin: 2px">|</span>
                                        <el-button :disabled="row.state == 1" type="primary" size="large" link @click="enablehandle(rowIndex, row)">
                                            {{ $t('启用') }}
                                        </el-button>
                                        <span v-if="row.id !== 1" style="margin: 2px">|</span>
                                        <el-button v-if="row.id !== 1" size="large" type="primary" link @click="copynew(rowIndex, row)">
                                            {{ $t('复制新增') }}
                                        </el-button>
                                        <span v-if="row.id !== 1" style="margin: 2px">|</span>
                                        <el-popconfirm v-if="row.id !== 1" :title="$t('确定要删除选中的方案吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deletedata(row['id'])" @cancel="null">
                                            <template #reference>
                                                <el-button v-loading="loading" type="danger" size="large" link style="margin-right: 10px">
                                                    {{ $t('删除') }}
                                                </el-button>
                                            </template>
                                        </el-popconfirm>
                                    </div>
                                    <div v-else>
                                        {{ row[column.prop] }}
                                    </div>
                                </template>
                            </vxe-column>
                        </vxe-table>
                        <pagemodel v-model:allcount="allcount" v-model:page="findform.page" v-model:pagecount="findform.pagecount" @pagechange="pagechange"></pagemodel>
                    </el-card>
                </div>
            </el-main>
        </el-container>
        <!-- 弹窗查看详情 -->
        <el-dialog v-model="dialogVisible" :title="formtitle" fullscreen :show-close="false">
            <template #header="{ close, titleId, titleClass }">
                <div>
                    <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><HomeFilled /></el-icon>{{ $t('菜单设置') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <div style="float: right">
                                <el-button :icon="Back" round @click="closeform()">{{ $t('返回') }}</el-button>
                                <el-button v-if="formdata.id !== 1" type="primary" round @click="onSubmit()"> {{ $t('确定') }} </el-button>
                                <UiSet :type="1" :index="1" :Prop="uiSectionList" :comid="componentId"  v-model:isgrant="isuigrantlist" @before-click="uisetbefore"></UiSet>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </template>

            <el-form v-loading="loading" :inline="true" :model="formdata" label-width="130" style="max-width: 1300px">
                <el-form-item :label="$t('方案名称')">
                    <el-input v-model="formdata.MenuName" :disabled="formdata.id == 1" />
                </el-form-item>
                <el-form-item :label="$t('启用状态')">
                    <el-switch v-model="formdata.state" :active-value="1" :inactive-value="0" :disabled="formdata.id == 1" />
                </el-form-item>
                <el-form-item :label="$t('使用角色')">
                    <el-input v-model="formdata.role" :disabled="formdata.id == 1" />
                </el-form-item>
                <el-form-item :label="$t('使用用户')">
                    <el-input v-model="formdata.user" :disabled="formdata.id == 1" />
                </el-form-item>
                <el-form-item :label="$t('描述')">
                    <el-input v-model="formdata.des" :disabled="formdata.id == 1" />
                </el-form-item>
            </el-form>
            <!-- prettier-ignore -->
            <vxe-table 
            ref="poptableRef"
            stripe
            :loading="loading" 
            :data="poptablelist" 
            border height="600" 
            :row-config="{isCurrent: true, isHover: true,drag: true}"
            :column-config="{ resizable: true }"
            :tree-config="{transform: true, rowField: 'id', parentField: 'parentid' }"
            :row-drag-config="rowDragConfig"
            @cell-click="SetCurrent">
                <vxe-column tree-node drag-sort width="100" fixed="left" ></vxe-column>
                <vxe-column v-for="(column, index) in Stores.comui[componentId][1].tableProps" 
                :field="column.prop" 
                :title="column.label" 
                :width="column.width" 
                :fixed="column.fixed" 
                :align="column.align">
                <template #header>
                  <div v-if="column.type === 'checkbox'">
                     <el-checkbox v-model="Allcheck" @change="CheckAllChange" />
                  </div>
                  <div v-else>
                     {{ I(column.label, column.labeleng) }}
                  </div>
                </template>
                <template #default="{ row, rowIndex }">
                        <div v-if="column.prop === 'function'">
                            <menufunctionmodel @updatedata="setfunction($event)"></menufunctionmodel>
                        </div>
                        <div v-else-if="column.prop === 'name'">
                                <el-input v-model="row[column.prop]" :readonly="formdata.id == 1" />
                        </div>
                        <div v-else-if="column.prop === 'visible'">
                              <el-switch v-model="row[column.prop]" :active-value="true" :inactive-value="false" :disabled="formdata.id==1"/>
                        </div>
                        <div v-else-if="column.type === 'action'">
                            <el-button size="large" type='primary' link @click="addrow(rowIndex, row)" :disabled="formdata.id==1">
                                {{ $t('新增') }}
                            </el-button>
                            <span style="margin: 2px">|</span>
                              <el-button size="large" type='danger'  link @click="deleterow(rowIndex, row)" :disabled="formdata.id==1">
                                       {{ $t('删除') }}
                              </el-button>
                        </div>
                        <div v-else-if="column.prop === 'state'">
                            <el-switch v-model="row.state" :active-value="1" :inactive-value="0" />
                        </div>
                        <div v-else>
                            {{ row[column.prop] }}
                        </div>
                </template>
                </vxe-column>
            </vxe-table>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { httpSend } from '@/utils/api';
import { getCurrentInstance, onMounted, ref, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { Refresh, Search, Plus, Delete } from '@element-plus/icons-vue';
//@ts-ignore
import Menu from '@/assets/menu.json';
/*组件*/
import UiSet from '@/components/share/UiSet.vue';
import excel from '@/components/share/excel.vue';
import menufunctionmodel from '@/components/share/menufunctionmodel.vue';
import pagemodel from '@/components/share/pagemodel.vue';
//@ts-ignore
import { TableUiSection } from '@/components/share/ui-set.interface.ts';
import * as XLSX from 'xlsx'; /*excel操作*/
//@ts-ignore
import { useshareStore } from '@/store'; /*pina管理*/
import { Back } from '@element-plus/icons-vue';
import {  chkgrant } from '@/globalmethods'; /*通用方法*/
const excelRef = ref(null);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
const { t } = useI18n(); //多语言
// 自定义字段配置
const componentId = 'custommenusetting';
let uiSectionList: TableUiSection[] = [
    {
        baseProps: [{ label: '方案名称', prop: 'MenuName', visible: true, readonly: false, type: 'string', ismore: false }],
        tableProps: [
            { label: '方案名称', labelex: '', labeleng: '', prop: 'MenuName', visible: true, readonly: false, width: '120', type: 'string', fixed: null, align: 'center' },
            { label: '状态', labelex: '', labeleng: '', prop: 'state', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '创建人', labelex: '', labeleng: '', prop: 'tabnm', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '创建时间', labelex: '', labeleng: '', prop: 'created_at', visible: true, readonly: false, width: '160', type: 'string', fixed: null, align: 'center' },
            { label: '修改人', labelex: '', labeleng: '', prop: 'modifier', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '修改时间', labelex: '', labeleng: '', prop: 'updated_at', visible: true, readonly: false, width: '160', type: 'date', fixed: null, align: 'center' },
            { label: '描述', labelex: '', labeleng: '', prop: 'des', visible: true, readonly: false, width: '200', type: 'string', fixed: null, align: 'center' },
            { label: '操作', labelex: '', labeleng: '', prop: 'action', visible: true, readonly: false, width: '300', type: 'action', fixed: 'right', align: 'center' },
        ],
    },
    {
        baseProps: [],
        tableProps: [
            { label: '菜单名称', labelex: '', labeleng: '', prop: 'name', visible: true, readonly: false, width: '300', type: 'string', fixed: null, align: 'center' },
            { label: '是否展示', labelex: '', labeleng: '', prop: 'visible', visible: true, readonly: false, width: '200', type: 'string', fixed: null, align: 'center' },
            { label: '对应功能', labelex: '', labeleng: '', prop: 'function', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '操作', labelex: '', labeleng: '', prop: 'action', visible: true, readonly: false, width: '250', type: 'action', fixed: 'right', align: 'center' },
        ],
    },
];
const loading = ref(false);
const findform = reactive({
    MenuName: null,
    page: 1,
    pagecount: 10,
});
let Allcheck = ref(false);
const allcount = ref(0); // 总数据条数
const tablelist = ref([]); // 表格数据
const poptablelist = ref([]); // 弹窗表格数据
const formtitle = ref('自定义菜单');
const dialogVisible = ref(false);
let formdata: any = reactive({}); // 弹窗数据
const rowDragConfig = reactive<VxeTablePropTypes.RowDragConfig<any>>({
    isCrossDrag: true,
});
const poptableRef = ref<VxeTableInstance<any>>();
let IsSave = true;
const Stores = useshareStore() as any;
let selectindex = null;
const isuigrant = ref(false);
const isuigrantlist = ref(false);
Stores.setcomui([componentId, uiSectionList]);
onMounted(() => {
    //加载权限
    isuigrant.value = chkgrant('菜单设置', 'customset');
    isuigrantlist.value = chkgrant('菜单设置', 'customset1');
    getuiset();
    gettablelist();
});

//获取配置数据
const getuiset = async () => {
    loading.value = true;
    let comdata = [];
    comdata[0] = componentId;
    comdata[1] = [];
    Object.assign(comdata[1], uiSectionList);
    const fd = new FormData();
    let data = { comid: componentId, userid: null };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getComUiSet', fd, false);
    if (res && res.code == 1) {
        if (res.data.length > 0) {
            let data = JSON.parse(res.data[0]['setjson']);
            // 如果数据依然是字符串，则需要再解析一次
            if (typeof data === 'string') {
                data = JSON.parse(data); // 第二次解析
            }
            if (data) {
                Object.assign(comdata[1], data);
            }
        }
    }
    loading.value = false;
    Stores.setcomui(comdata);
};

const gettablelist = async () => {
    if (!chkgrant('菜单设置', 'Menufindlist')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    loading.value = true;
    tablelist.value = [];
    const fd = new FormData();
    fd.append('param', JSON.stringify(findform));
    const res = await httpSend('Menufindlist', fd, false);
    if (res && res.data && res.code == 1) {
        tablelist.value = res.data;
        allcount.value = res.count;
    }
    loading.value = false;
    IsSave = false;
};

//打开新增form
const append = () => {
    if (!chkgrant('菜单设置', 'Menusave')) {
        ElMessage.warning(t('您暂无新增权限,请联系管理员!'));
        return;
    }
    formdata.id = null;
    formdata.MenuName = null;
    formdata.state = false;
    formdata.des = null;
    formdata.role = null;
    formdata.user = null;
    formdata.roleid = null;
    formdata.userid = null;
    poptablelist.value = flattenTree(Menu);
    dialogVisible.value = true;
};
//删除数据
const deletedata = async (id: any) => {
    if (!chkgrant('菜单设置', 'Menudelete')) {
        ElMessage.warning(t('您暂无删除权限,请联系管理员!'));
        return;
    }
    loading.value = true;
    tablelist.value = [];
    let senddata = { id: id, page: findform.page, pagecount: findform.pagecount, MenuName: findform.MenuName };
    const fd = new FormData();
    fd.append('param', JSON.stringify(senddata));
    const res = await httpSend('Menudelete', fd, false);
    if (res && res.data && res.code == 1) {
        tablelist.value = res.data;
        allcount.value = res.count;
    }
    loading.value = false;
    IsSave = false;
};
//复制新增
const copynew = (index: any, data: any) => {
    if (!chkgrant('菜单设置', 'Menusave')) {
        ElMessage.warning(t('您暂无新增权限,请联系管理员!'));
        return;
    }
    poptablelist.value = [];
    if (data.MenuName == '系统默认菜单') {
        poptablelist.value = flattenTree(Menu);
    } else {
        let param = { id: data.id };
        lookdetail(-1, param, true);
    }
    dialogVisible.value = true;
};
//菜单启用
const enablehandle = async (index: any, data: any) => {
    if (!chkgrant('菜单设置', 'Menuenablehandle')) {
        ElMessage.warning(t('您暂无启用权限,请联系管理员!'));
        return;
    }
    loading.value = true;
    tablelist.value = [];
    let senddata = { id: data.id, page: findform.page, pagecount: findform.pagecount, MenuName: findform.MenuName };
    const fd = new FormData();
    fd.append('param', JSON.stringify(senddata));
    const res = await httpSend('Menuenablehandle', fd);
    if (res && res.data && res.code == 1) {
        tablelist.value = res.data;
        allcount.value = res.count;
    }
    loading.value = false;
    IsSave = false;
};
//查看详情
const lookdetail = async (index: any, data: any, iscopynew: any) => {
    if (!chkgrant('菜单设置', 'Menufinddetail')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    poptablelist.value = [];
    //系统默认菜单直接赋值
    if (data.id == 1) {
        formdata.id = data.id;
        formdata.MenuName = data.MenuName;
        formdata.state = data.state;
        formdata.role = data.role;
        formdata.user = data.user;
        formdata.des = data.des;
        formdata.roleid = data.roleid;
        formdata.userid = data.userid;
        poptablelist.value = flattenTree(Menu);
    } else {
        const fd = new FormData();
        fd.append('param', JSON.stringify({ id: data.id }));
        const res = await httpSend('Menufinddetail', fd, false);
        if (res && res.data && res.code == 1) {
            if (res.data.length > 0) {
                formdata.MenuName = res.data[0].MenuName;
                formdata.state = false;
                formdata.role = res.data[0].role;
                formdata.user = res.data[0].user;
                formdata.roleid = res.data[0].roleid;
                formdata.userid = res.data[0].userid;
                //复制新增的不赋值下面属性，只获取table数据
                if (!iscopynew) {
                    formdata.state = res.data[0].state;
                    formdata.id = res.data[0].id;
                    formdata.des = res.data[0].des;
                }
                let data = JSON.parse(res.data[0]['datatext']);
                // 如果数据依然是字符串，则需要再解析一次
                if (typeof data === 'string') {
                    data = JSON.parse(data); // 第二次解析
                }
                if (data) {
                    Object.assign(poptablelist.value, flattenTree(data));
                }
            }
        }
        loading.value = false;
    }

    dialogVisible.value = true;
};
//把多维数据转成一维,isover=true 只解析两层
function flattenTree(tree, parentid = null, isover = false) {
    return tree.reduce((acc, item) => {
        acc.push({
            id: item.id,
            name: item.name,
            icon: item.icon,
            selected: item.selected,
            open: item.open,
            visible: item.visible,
            hidden: item.hidden,
            query: item.query,
            path: item.path,
            parentid: parentid,
            // 可以在这里添加其他你需要的属性
        });
        if (item.children && item.children.length && !isover) {
            acc.push(...flattenTree(item.children, item.id, true));
        }
        return acc;
    }, []);
}

//选择功能
const setfunction = (e: any) => {
    poptablelist.value[selectindex].path = e.path;
    poptablelist.value[selectindex].id = e.id;
    poptablelist.value[selectindex].icon = e.icon;
    poptablelist.value[selectindex].selected = e.selected;
    poptablelist.value[selectindex].open = e.open;
    poptablelist.value[selectindex].visible = e.visible;
    poptablelist.value[selectindex].hidden = e.hidden;
    poptablelist.value[selectindex].query = e.query;
};

//新增行
const addrow = async (index: any, row: any) => {
    const $table = poptableRef.value;
    if ($table) {
        const record = {
            MenuName: null,
            visible: null,
            function: null,
        };
        await $table.insertAt(record, row);
    }
};
//删除行
const deleterow = (index: any, row: any) => {
    const $table = poptableRef.value;
    if ($table) {
        $table.remove(row);
    }
};

const closeform = () => {
    dialogVisible.value = false;
    if (IsSave) {
        gettablelist();
    }
};

//重置
const resetForm = () => {
    for (let key in findform) {
        if (findform.hasOwnProperty(key)) {
            findform[key] = null;
        }
    }
};
//页数变化重新查询
const pagechange=(e)=>{
    gettablelist();
}

//保存
const onSubmit = async () => {
    if (!chkgrant('菜单设置', 'Menusave')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    if (formdata.MenuName == null || formdata.MenuName == '') {
        ElMessage.warning(t('方案名称不能为空'));
        return;
    }

    let data = JSON.parse(JSON.stringify(formdata));
    const $table = poptableRef.value;
    if ($table) {
        data['tablist'] = $table.getFullData();
    }
    const fd = new FormData();
    fd.append('param', JSON.stringify(data));
    loading.value = true;
    try {
        const res = await httpSend('Menusave', fd);
        if (res.code === 1) {
            formdata.id = res.id;
            IsSave = true;
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
//单选
const SetCurrent = (e) => {
    selectindex = e.$rowIndex;
};
//自定义配置权限判断
const uisetbefore = () => {
    if (!isuigrant.value) {
        ElMessage.warning(t('您暂无配置权限,请联系管理员!'));
        return;
    }
};
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>
<style scoped>
:deep(.el-header) {
    --el-header-padding: 0 20px;
    --el-header-height: 60px;
    box-sizing: border-box;
    flex-shrink: 0;
    height: auto;
    padding: 0;
}
:deep(.el-card__body) {
    padding: 5px !important;
    color: #000000;
}
</style>
